"""
下载 Live2D 所需的 JavaScript 库到本地
"""

import urllib.request
import os
from pathlib import Path

# 库文件下载列表
libraries = [
    {
        'name': 'PIXI.js',
        'url': 'https://cdn.bootcdn.net/ajax/libs/pixi.js/7.4.2/pixi.min.js',
        'filename': 'pixi.min.js',
        'alternatives': [
            'https://unpkg.com/pixi.js@7.4.2/dist/pixi.min.js',
            'https://cdnjs.cloudflare.com/ajax/libs/pixi.js/7.4.2/pixi.min.js'
        ]
    },
    {
        'name': 'Live2D Cubism Core',
        'url': 'https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js',
        'filename': 'live2dcubismcore.min.js',
        'alternatives': []
    }
]

def download_file(url, dest_path, desc=""):
    """下载文件"""
    try:
        print(f"  正在下载 {desc}...")
        print(f"  URL: {url}")
        
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=30) as response:
            data = response.read()
            
            with open(dest_path, 'wb') as f:
                f.write(data)
        
        file_size = len(data) / 1024  # KB
        print(f"  ✓ 下载成功 ({file_size:.1f} KB)")
        return True
        
    except Exception as e:
        print(f"  ✗ 下载失败: {e}")
        return False


def main():
    """主函数"""
    print("=" * 70)
    print("下载 Live2D JavaScript 库")
    print("=" * 70)
    
    # 创建 libs 目录
    libs_dir = Path(__file__).parent / 'libs'
    libs_dir.mkdir(exist_ok=True)
    
    print(f"\n目标目录: {libs_dir}\n")
    
    success_count = 0
    total_count = len(libraries)
    
    for lib in libraries:
        print(f"📦 {lib['name']}")
        dest_path = libs_dir / lib['filename']
        
        # 如果文件已存在且大小正常，跳过
        if dest_path.exists() and dest_path.stat().st_size > 1000:
            print(f"  ✓ 文件已存在，跳过")
            success_count += 1
            continue
        
        # 尝试主URL
        if download_file(lib['url'], dest_path, lib['name']):
            success_count += 1
            continue
        
        # 尝试备用URL
        downloaded = False
        for alt_url in lib['alternatives']:
            print(f"  尝试备用源...")
            if download_file(alt_url, dest_path, lib['name']):
                success_count += 1
                downloaded = True
                break
        
        if not downloaded:
            print(f"  ⚠ 所有源都失败，请手动下载")
        
        print()
    
    print("=" * 70)
    print(f"下载完成: {success_count}/{total_count} 个文件")
    print("=" * 70)
    
    if success_count < total_count:
        print("\n⚠ 部分文件下载失败")
        print("建议：手动下载缺失的文件到 libs/ 目录")
    else:
        print("\n✓ 所有库文件已准备就绪")
        print("\n下一步：")
        print("  访问 http://localhost:8000/web_live2d_local.html")
    
    return 0 if success_count == total_count else 1


if __name__ == "__main__":
    import sys
    sys.exit(main())
